<template>
  <div class="electric-anomaly-container">
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	        <el-col :span="24" class="text-center">
	            <div class="title-wrapper">
	            <i class="el-icon-search el-icon--large"></i>
	            <h1 class="main-title">电线监测管理系统</h1>
	            <p class="sub-title">精准追踪电线检测动态，及时更新线路安全信息，以专业检测消除用电风险，守护每一处空间的平安用电</p>
	            </div>
	        </el-col>
	    </el-row>
    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="电线异常详情"
      width="70%"
      destroy-on-close
    >
      <el-descriptions title="异常信息" direction="vertical" :column="4" :model="anomalyMessage" border>
        <el-descriptions-item label="异常ID" :span="2">{{ anomalyMessage.anomalyId }}</el-descriptions-item>
        <el-descriptions-item label="地点ID" :span="2">{{ anomalyMessage.locationId }}</el-descriptions-item>
        <el-descriptions-item label="错误信息" :span="2">{{ anomalyMessage.errorMessage }}</el-descriptions-item>
        <el-descriptions-item label="紧急状态" :span="2">{{ anomalyMessage.urgencyStatus }}</el-descriptions-item>
        <el-descriptions-item label="处理状态" :span="2">{{ anomalyMessage.processingStatus }}</el-descriptions-item>
        <el-descriptions-item label="记录时间" :span="2">{{ formatDate(anomalyMessage.recordTime) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible1"
      title="编辑电线异常"
      width="70%"
      destroy-on-close
    >
      <el-form 
        :model="ruleForm" 
        :rules="rules" 
        ref="ruleFormRef" 
        label-width="120px" 
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="异常ID" prop="anomalyId">
              <el-input v-model="ruleForm.anomalyId" placeholder="异常ID" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地点ID" prop="locationId">
              <el-input v-model="ruleForm.locationId" placeholder="地点ID"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="错误信息" prop="errorMessage">
              <el-input v-model="ruleForm.errorMessage" placeholder="错误信息"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="紧急状态" prop="urgencyStatus">
              <el-select v-model="ruleForm.urgencyStatus" placeholder="紧急状态">
                <el-option label="高" value="高"></el-option>
                <el-option label="中" value="中"></el-option>
                <el-option label="低" value="低"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="处理状态" prop="processingStatus">
              <el-select v-model="ruleForm.processingStatus" placeholder="处理状态">
                <el-option label="未处理" value="未处理"></el-option>
                <el-option label="处理中" value="处理中"></el-option>
                <el-option label="已处理" value="已处理"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-button type="primary" @click="formSubmit()">确 定</el-button>
            <el-button @click="dialogVisible1 = false">取 消</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- 添加对话框 -->
    <el-dialog
      v-model="dialogVisible2"
      title="添加电线异常"
      width="70%"
      destroy-on-close
    >
      <el-form 
        :model="addForm" 
        :rules="addRules" 
        ref="addFormRef" 
        label-width="120px" 
        class="demo-ruleForm"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="地点ID" prop="locationId">
              <el-input v-model="addForm.locationId" placeholder="地点ID"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="错误信息" prop="errorMessage">
              <el-input v-model="addForm.errorMessage" placeholder="错误信息"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="紧急状态" prop="urgencyStatus">
              <el-select v-model="addForm.urgencyStatus" placeholder="紧急状态">
                <el-option label="高" value="高"></el-option>
                <el-option label="中" value="中"></el-option>
                <el-option label="低" value="低"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="处理状态" prop="processingStatus">
              <el-select v-model="addForm.processingStatus" placeholder="处理状态">
                <el-option label="未处理" value="未处理"></el-option>
                <el-option label="处理中" value="处理中"></el-option>
                <el-option label="已处理" value="已处理"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-button type="primary" @click="addSubmit()">确 定</el-button>
            <el-button @click="dialogVisible2 = false">取 消</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- 搜索和操作区 -->
    <el-row :gutter="20" style="width: 100%; margin-bottom: 20px;">
      <el-col :span="12">
        <el-input 
          placeholder="请输入错误信息查询" 
          v-model="searchQuery" 
          style="width: 70%;"
          @keyup.enter="handleSearch"
        ></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch()" style="margin-left: 10px;">搜索</el-button>
      </el-col>
      <el-col :span="12" class="text-right">
        <el-button type="primary" icon="el-icon-plus" @click="openDetails2()">添加</el-button>
      </el-col>
    </el-row>

    <!-- 表格部分 -->
    <el-table 
      :data="tableData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
      border 
      style="width: 100%"
      height="450"
      :row-class-name="tableRowClassName"
    >
      <el-table-column prop="anomalyId" label="编号" width="150" align="center" />
      <el-table-column prop="locationId" label="地点" width="150" align="center" />
      <el-table-column prop="errorMessage" label="错误信息" width="150" align="center" />
      <el-table-column prop="urgencyStatus" label="紧急状态" align="center" />
      <el-table-column prop="processingStatus" label="处理状态" width="140" align="center">
        <template #default="scope">
          <el-select v-model="scope.row.processingStatus" @change="() => updateRowStatus(scope.$index, scope.row)" placeholder="处理状态">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="recordTime" label="时间" align="center" />
      <el-table-column label="操作" width="240" align="center">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button type="primary" size="mini" @click="openDetails(scope.row)">查看</el-button>
            <el-button type="warning" size="mini" @click="openDetails1(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-row type="flex" justify="center" style="margin-top: 20px;">
      <el-pagination 
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5,10,20,50]" 
        :page-size="pageSize" 
        :total="tableData.length"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus';
import { post, get } from '@/utils/axios';

// 对话框控制变量
const dialogVisible = ref(false);
const dialogVisible1 = ref(false);
const dialogVisible2 = ref(false);

// 搜索和分页变量
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(5);
const tableData = ref([]);

// 表单引用
const ruleFormRef = ref(null);
const addFormRef = ref(null);

// 编辑时保存原始数据（用于对比修改字段）
const originalRow = ref({});

// 详情数据对象
const anomalyMessage = reactive({
  anomalyId: '',
  locationId: '',
  errorMessage: '',
  urgencyStatus: '',
  processingStatus: '',
  recordTime: ''
});

// 编辑表单数据
const ruleForm = reactive({
  anomalyId: '',
  locationId: '',
  errorMessage: '',
  urgencyStatus: '',
  processingStatus: ''
});

// 新增表单数据
const addForm = reactive({
  locationId: '',
  errorMessage: '',
  urgencyStatus: '',
  processingStatus: ''
});

// 编辑表单校验规则（可选化）
const rules = reactive({
  locationId: [
    { 
      validator: (rule, value, callback) => {
        if (!value) callback(); // 不填则通过（保留原值）
        else callback();
      }, 
      trigger: 'blur' 
    }
  ],
  errorMessage: [
    { 
      validator: (rule, value, callback) => {
        if (!value) callback(); // 不填则通过（保留原值）
        else callback();
      }, 
      trigger: 'blur' 
    }
  ],
  urgencyStatus: [
    { 
      validator: (rule, value, callback) => {
        // 没选紧急状态但原始数据有 → 不修改，通过
        if (!value && originalRow.value.urgencyStatus) callback();
        else if (value) callback();
        else callback(new Error('请选择紧急状态（若需修改）'));
      }, 
      trigger: 'change' 
    }
  ],
  processingStatus: [
    { 
      validator: (rule, value, callback) => {
        // 没选处理状态但原始数据有 → 不修改，通过
        if (!value && originalRow.value.processingStatus) callback();
        else if (value) callback();
        else callback(new Error('请选择处理状态（若需修改）'));
      }, 
      trigger: 'change' 
    }
  ]
});

// 新增表单校验规则（保持必填字段）
const addRules = reactive({
  locationId: [
    { required: true, message: '请输入地点ID', trigger: 'blur' }
  ],
  errorMessage: [
    { required: true, message: '请输入错误信息', trigger: 'blur' }
  ],
  urgencyStatus: [
    { required: true, message: '请选择紧急状态', trigger: 'change' }
  ],
  processingStatus: [
    { required: true, message: '请选择处理状态', trigger: 'change' }
  ]
});

const options = [
  { value: '未处理', label: '未处理' },
  { value: '处理中', label: '处理中' },
  { value: '已处理', label: '已处理' }
]

// 日期格式化
const formatDate = (dateValue) => {
  if (!dateValue) return '';
  const date = typeof dateValue === 'string' ? new Date(dateValue) : dateValue;
  if (isNaN(date.getTime())) return '';
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
};

// 表格行样式
const tableRowClassName = ({ row }) => {
  const statusColorMap = { '未处理': 'red-row', '处理中': 'yellow-row', '已处理': 'green-row' };
  return statusColorMap[row.processingStatus] || '';
};

// 打开详情对话框
const openDetails = (row) => {
  dialogVisible.value = true;
  Object.assign(anomalyMessage, row);
};

// 打开编辑对话框（保存原始数据）
const openDetails1 = (row) => {
  dialogVisible1.value = true;
  // 深拷贝原始数据（避免双向绑定）
  originalRow.value = JSON.parse(JSON.stringify(row));
  const temp = JSON.parse(JSON.stringify(row));
  Object.assign(ruleForm, temp);
};

// 打开新增对话框
const openDetails2 = () => {
  dialogVisible2.value = true;
  // 重置表单
  if (addFormRef.value) addFormRef.value.resetFields();
  Object.keys(addForm).forEach(key => addForm[key] = '');
};

// 分页处理
const handleSizeChange = (val) => { pageSize.value = val; currentPage.value = 1; };
const handleCurrentChange = (val) => { currentPage.value = val; };

// 编辑提交
const formSubmit = () => {
  ruleFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '修改中...' });
    post('/sc/anomalies/update', ruleForm, (res) => {
      loading.close();
      if (res.state === 'success') {
        ElMessage.success('修改成功！');
        dialogVisible1.value = false;
        fetchTableData();
      } else {
        ElMessage.error(res.message || '修改失败');
      }
    }, (err) => {
      loading.close();
      ElMessage.error('请求失败：' + (err.message || '网络异常'));
    });
  });
};

// 新增提交
const addSubmit = () => {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '添加中...' });
    post('/sc/anomalies/add', addForm, (res) => {
      loading.close();
      if (res.state === 'success') {
        ElMessage.success('添加成功！');
        dialogVisible2.value = false;
        // 重置表单
        if (addFormRef.value) addFormRef.value.resetFields();
        Object.keys(addForm).forEach(key => addForm[key] = '');
        fetchTableData();
      } else {
        ElMessage.error(res.message || '添加失败');
      }
    }, (err) => {
      loading.close();
      ElMessage.error('请求失败：' + (err.message || '网络异常'));
    });
  });
};

// 搜索处理
const handleSearch = () => {
  const loading = ElLoading.service({ text: '搜索中...' });
  if (!searchQuery.value.trim()) {
    fetchTableData();
    loading.close();
    return;
  }
  get('/sc/anomalies/byErrorMessage', { errorMessage: searchQuery.value }, (res) => {
    loading.close();
    if (res.state === 'success') {
      tableData.value = res.data;
      ElMessage.success(res.message);
    } else {
      tableData.value = [];
      ElMessage.warning(res.message || '未找到匹配记录');
    }
  }, (err) => {
    loading.close();
    ElMessage.error('搜索失败：' + (err.message || '网络异常'));
  });
};

// 更新行状态
const updateRowStatus = (index, row) => {
  const loading = ElLoading.service({ text: '更新中...' });
  post('/sc/anomalies/updateStatus', {
    anomalyId: row.anomalyId,
    processingStatus: row.processingStatus
  }, (res) => {
    loading.close();
    if (res.state === 'success') {
      ElMessage.success('状态更新成功');
      fetchTableData();
    } else {
      ElMessage.error(res.message || '状态更新失败');
      // 恢复原状态
      fetchTableData();
    }
  }, (err) => {
    loading.close();
    ElMessage.error('请求失败：' + (err.message || '网络异常'));
    // 恢复原状态
    fetchTableData();
  });
};

// 删除处理
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这条异常记录吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const loading = ElLoading.service({ text: '删除中...' });
    post('/sc/anomalies/delete', { anomalyId: row.anomalyId }, (res) => {
      loading.close();
      if (res.state === 'success') {
        ElMessage.success('删除成功！');
        fetchTableData();
      } else {
        ElMessage.error(res.message || '删除失败');
      }
    }, (err) => {
      loading.close();
      ElMessage.error('请求失败：' + (err.message || '网络异常'));
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 获取表格数据
const fetchTableData = () => {
  const loading = ElLoading.service({ text: '加载中...' });
  get('/sc/anomalies/byDianCategory', {}, (res) => {
    loading.close();
    if (res.status) {
      tableData.value = res.data;
    } else {
      ElMessage.error(res.message || '获取数据失败');
    }
  }, (err) => {
    loading.close();
    ElMessage.error('请求失败：' + (err.message || '网络异常'));
  });
};

// 初始化加载数据
onMounted(() => {
  fetchTableData();
});
</script>

<style scoped>
	
/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}
.electric-anomaly-container {
  padding: 20px;
}

.text-right {
  text-align: right;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

/* 表格行样式 */
:deep(.red-row) {
  --el-table-tr-bg-color: var(--el-color-danger-light-9);
}
:deep(.yellow-row) {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
:deep(.green-row) {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>


